#include "udp_server.h"
#include <iostream>

namespace umtl
{
	//////////////////////////////////////////////////////////////////////////
	//

	udp_server::udp_server( unsigned short int port, udp_server::read_handler_t read_handler, udp_server::close_handler_t close_handler )
		: server( port, read_handler, close_handler )
		, accpet_connection_(0)
		, port_( port )
	{
		read_handler_ = [this, read_handler]( connection * conn, char const * data, size_t len )
		{
			if( accpet_connection_ != conn )
			{
				conn->send( "ok", 3 );
				accpet_connection_ = conn;
			}
			read_handler( conn, data, len );
		};

		try
		{
			start_receive(read_handler_);
		}
		catch(std::exception & e)
		{
			std::cerr << e.what() << std::endl;
		}
	}

	//////////////////////////////////////////////////////////////////////////
	//

	void udp_server::start_receive( udp_server::read_handler_t read_handler )
	{
		connection * connection = connection::create( read_handler, close_handler_ );
		connection->listen( port_ );

		connection->read();
		connection->run();

		insertConnection( connection );
	}

	//////////////////////////////////////////////////////////////////////////
}